from django.shortcuts import render
# 导入日期模块
from datetime import datetime, timedelta
from utils import sqlhelper
import json


def echart_basic(request):
    #  提供默认的值
    city = "上海市"
    today_date = datetime.now()

    # 判断是不是post请求
    if request.method == "POST":
        if len(request.POST.get('q_city')) != 0:
            city = request.POST.get('q_city')

        # 处理接收的日期
        date_str = (request.POST.get('q_date')).split("-")
        today_date = datetime(int(date_str[0]), int(date_str[1]), int(date_str[2]), 0, 0, 0)

    # ==== 准备传递到前台数据=====
    data = {}
    # 添加城市
    data['city'] = city
    # 添加日期
    data['today'] = today_date.strftime("%Y-%m-%d")
    # 添加天气
    data['temp'] = get_hight_low_temp(city, today_date)
    # 添加全国温差最大的10个城市
    data['diff_top_10'] = get_diff_temp(today_date)

    # ========返回到前端页面==============
    return render(request, 'echartsweb/echarts_demo1.html', {'weather': json.dumps(data)})


def get_hight_low_temp(city, today):
    """获取某一个城市未来7天的天气"""
    # 获取今天的日期

    today_str = today.strftime("%Y-%m-%d")
    seven_day = (today + timedelta(days=7)).strftime("%Y-%m-%d")
    # 准备sql
    sql = "Select Date, Hight, Low from CityWeather where Date>='%s' and Date<='%s' and Area='%s';" % (
        today_str, seven_day, city)
    # 获取数据
    response = sqlhelper.get_db_data(sql)
    # 准备三组数据  -- temp = { 'date' :[], 'hight:[], 'low': []}
    temp = {'date': [], 'hight': [], 'low': []}
    # 遍历
    for value in response['data']:
        temp['date'].append(value[0].strftime("%m-%d"))
        temp['hight'].append(value[1])
        temp['low'].append(value[2])
    # 返回
    return temp


def get_diff_temp(today):
    # 准备sql
    sql = """
    Select  Area, Hight,Low, Hight-Low
    from  CityWeather
    where Date = '%s'
    Order By (Hight-Low) DESC
    Limit 10
    """ % (today.strftime('%Y-%m-%d'))
    # 执行
    response = sqlhelper.get_db_data(sql)
    # 结果
    res = {'city': [], 'hight': [], 'low': [], 'diff': []}
    # 遍历
    for value in response['data']:
        res['city'].append(value[0][0:3])
        res['hight'].append(value[1])
        res['low'].append(value[2])
        res['diff'].append(value[3])
    # 返回
    return res


def echart_china_map(request):
    # 初始化今天
    today_date = datetime.now().strftime("%Y-%m-%d")
    # 判断是不是post请求
    if request.method == "POST":
        today_date = request.POST.get('q_date')

    data = {}
    # 添加城市
    data['date'] = today_date
    # 附加温度信息
    data['map'] = get_china_map_temp(today_date)

    # ========返回到前端页面==============
    return render(request, 'echartsweb/chinamapecharts.html', {'weather': json.dumps(data)})



def get_china_map_temp(date_str):
    # 获取某一个天全国各个省、直辖市、自治区的平均最高温度、最低温度、温差
    sql = """
        Select T1.Province, AVG(Hight) ,AVG(Low),AVG(Hight-Low) From CityURL As T1
    Inner Join CityWeather As T2  on T1.Area = T2.Area 
    where Date ='%s' 
    Group By T1.Province
    """ % (date_str)
    # 执行
    response = sqlhelper.get_db_data(sql)
    # 准备返回值
    res = {'hight':[],'low':[], 'diff':[]}
    # 遍历
    for value in response['data']:
        province = value[0][0:2]
        if province == "黑龙":
            province += '江'
        if province == "内蒙":
            province += '古'
        # 定义最高温度的临时字典
        res['hight'].append({'name': province, 'value': int(round(value[1],2))})
        res['low'].append({'name': province, 'value': int(round(value[2],2))})
        res['diff'].append({'name': province, 'value': int(round(value[3],2))})

    # 返回
    return res
